<template>
  <div class="user-list">
    <a-card title="用户管理" :bordered="false">
      <!-- 搜索区域 -->
      <div class="search-area">
        <a-form layout="inline" :model="searchForm">
          <a-form-item label="用户名">
            <a-input v-model:value="searchForm.username" placeholder="请输入用户名" />
          </a-form-item>
          <a-form-item label="手机号">
            <a-input v-model:value="searchForm.phone" placeholder="请输入手机号" />
          </a-form-item>
          <a-form-item label="状态">
            <a-select v-model:value="searchForm.status" placeholder="请选择状态" style="width: 120px">
              <a-select-option value="">全部</a-select-option>
              <a-select-option :value="1">正常</a-select-option>
              <a-select-option :value="0">禁用</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item>
            <a-button type="primary" @click="handleSearch">搜索</a-button>
            <a-button style="margin-left: 8px" @click="handleReset">重置</a-button>
          </a-form-item>
        </a-form>
      </div>

      <!-- 操作按钮区域 -->
      <div class="action-area">
        <a-button type="primary" @click="handleAdd">
          <plus-outlined />
          新增用户
        </a-button>
      </div>

      <!-- 表格区域 -->
      <a-table
        :columns="columns"
        :data-source="userList"
        :loading="loading"
        :pagination="pagination"
        row-key="id"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <a-tag :color="record.status === 1 ? 'green' : 'red'">
              {{ record.statusName || (record.status === 1 ? '正常' : '禁用') }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="handleEdit(record)">编辑</a-button>
              <a-button type="link" size="small" @click="handleView(record)">查看</a-button>
              <a-popconfirm
                title="确定要删除这个用户吗？"
                @confirm="handleDelete(record)"
              >
                <a-button type="link" size="small" danger>删除</a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 用户表单模态框 -->
    <a-modal
      v-model:open="modalVisible"
      :title="modalTitle"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
      width="600px"
    >
      <a-form
        ref="formRef"
        :model="form"
        :rules="rules"
        layout="vertical"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="用户名" name="username">
              <a-input v-model:value="form.username" placeholder="请输入用户名" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="昵称" name="nickname">
              <a-input v-model:value="form.nickname" placeholder="请输入昵称" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="手机号" name="phone">
              <a-input v-model:value="form.phone" placeholder="请输入手机号" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="邮箱" name="email">
              <a-input v-model:value="form.email" placeholder="请输入邮箱" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="密码" name="password" v-if="!form.id">
              <a-input-password v-model:value="form.password" placeholder="请输入密码" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="状态" name="status">
              <a-select v-model:value="form.status" placeholder="请选择状态">
                <a-select-option :value="1">正常</a-select-option>
                <a-select-option :value="0">禁用</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="24">
            <a-form-item label="分配角色" name="roleIds">
              <a-select
                v-model:value="form.roleIds"
                mode="multiple"
                placeholder="请选择角色"
                :options="roleOptions"
                :loading="roleLoading"
                option-label-prop="label"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-form-item label="备注" name="remark">
          <a-textarea v-model:value="form.remark" placeholder="请输入备注" :rows="3" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { getUserPage, addUser, updateUser, deleteUser } from '@/api/user'
import { getRoleList, getUserRoles, assignUserRoles } from '@/api/role'

// 响应式数据
const loading = ref(false)
const userList = ref([])
const modalVisible = ref(false)
const modalTitle = ref('新增用户')
const formRef = ref()

// 搜索表单
const searchForm = reactive({
  username: '',
  phone: '',
  status: ''
})

const roleOptions = ref([])
const roleLoading = ref(false)

// 用户表单
const form = reactive({
  id: '',
  username: '',
  nickname: '',
  phone: '',
  email: '',
  password: '',
  status: 1,
  remark: '',
  roleIds: []
})

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total) => `共 ${total} 条记录`
})

// 表格列配置
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 80
  },
  {
    title: '用户名',
    dataIndex: 'username',
    key: 'username'
  },
  {
    title: '昵称',
    dataIndex: 'nickname',
    key: 'nickname'
  },
  {
    title: '手机号',
    dataIndex: 'phone',
    key: 'phone'
  },
  {
    title: '邮箱',
    dataIndex: 'email',
    key: 'email'
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status'
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime'
  },
  {
    title: '操作',
    key: 'action',
    width: 200
  }
]

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于 6 个字符', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 获取用户列表
const fetchUserList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.current,
      size: pagination.pageSize,
      username: searchForm.username || undefined,
      phone: searchForm.phone || undefined,
      status: searchForm.status || undefined
    }
    const res = await getUserPage(params)
    userList.value = res.data.data.records || []
    pagination.total = res.data.data.total || 0
  } catch (error) {
    message.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchUserList()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    username: '',
    phone: '',
    status: ''
  })
  pagination.current = 1
  fetchUserList()
}

// 表格变化
const handleTableChange = (pag) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  fetchUserList()
}

// 获取所有角色
const fetchRoleOptions = async () => {
  roleLoading.value = true
  try {
    const res = await getRoleList()
    roleOptions.value = (res.data.data || []).map(r => ({ label: r.name, value: r.id }))
  } finally {
    roleLoading.value = false
  }
}

// 获取用户已分配角色
const fetchUserRoleIds = async (userId) => {
  if (!userId) {
    form.roleIds = []
    return
  }
  const res = await getUserRoles(userId)
  form.roleIds = (res.data.data || []).map(r => r.id)
}

// 新增用户
const handleAdd = async () => {
  modalTitle.value = '新增用户'
  Object.assign(form, {
    id: '',
    username: '',
    nickname: '',
    phone: '',
    email: '',
    password: '',
    status: 1,
    remark: '',
    roleIds: []
  })
  await fetchRoleOptions()
  modalVisible.value = true
}

// 编辑用户
const handleEdit = async (record) => {
  modalTitle.value = '编辑用户'
  Object.assign(form, record)
  await fetchRoleOptions()
  await fetchUserRoleIds(record.id)
  modalVisible.value = true
}

// 查看用户
const handleView = (record) => {
  modalTitle.value = '查看用户'
  Object.assign(form, record)
  modalVisible.value = true
}

// 删除用户
const handleDelete = async (record) => {
  try {
    const res = await deleteUser(record.id)
    if (res.data && res.data.code === 200) {
      message.success('删除成功')
      fetchUserList()
    } else {
      message.error(res.data?.message || '删除失败')
    }
  } catch (error) {
    message.error('删除失败')
  }
}

// 模态框确认
const handleModalOk = async () => {
  try {
    await formRef.value.validate()
    let res
    if (form.id) {
      res = await updateUser(form)
      if (res.data && res.data.code === 200) {
        message.success('更新成功')
      } else {
        message.error(res.data?.message || '更新失败')
        return
      }
    } else {
      res = await addUser(form)
      if (res.data && res.data.code === 200) {
        message.success('添加成功')
      } else {
        message.error(res.data?.message || '添加失败')
        return
      }
    }
    // 分配角色
    if (form.roleIds && form.roleIds.length > 0 && form.id) {
      await assignUserRoles(form.id, form.roleIds)
    }
    modalVisible.value = false
    fetchUserList()
  } catch (error) {
    message.error('表单提交失败')
  }
}

// 模态框取消
const handleModalCancel = () => {
  modalVisible.value = false
  formRef.value?.resetFields()
}

// 初始化
onMounted(() => {
  fetchUserList()
})
</script>

<style scoped>
.user-list {
  padding: 24px;
}

/* 保留 search-area 和 action-area 局部样式，其余交给全局 */
.search-area {
  margin-bottom: 16px;
  padding: 16px;
  background: #fafafa;
  border-radius: 10px;
}

.action-area {
  margin-bottom: 16px;
}

@media (max-width: 600px) {
  .user-list {
    padding: 4px !important;
  }
  .search-area {
    padding: 8px !important;
    margin-bottom: 8px !important;
    flex-direction: column !important;
  }
  .action-area {
    margin-bottom: 8px !important;
  }
  .ant-table {
    font-size: 12px !important;
    overflow-x: auto !important;
    min-width: 480px;
  }
  .ant-table-thead > tr > th,
  .ant-table-tbody > tr > td {
    padding: 4px 6px !important;
  }
}
</style>
